<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 开发环境版本，包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <style>
        
    </style>
</head>
<body>
    <div id="aaa">
        <table id="tab" border="1" cellpadding="20" cellspacing="0" align="center">
            <tr>
                <td>
                    {{goods[0].name}}
                </td>
                <td>
                    单价 {{goods[0].price}}
                </td>
                <td>
                    <button @click="subtraction(0)">-</button>
                    {{goods[0].num}}
                    <button v-on:click="add(0)">+</button>
                </td>
            </tr>
            <tr>
                <td>
                    {{goods[1].name}}
                </td>
                <td>
                    单价 {{goods[1].price}}
                </td>
                <td>
                    <button @click="subtraction(1)">-</button>
                    {{goods[1].num}}
                    <button v-on:click="add(1)">+</button>
                </td>
            </tr>
            <tr>
                <td>
                    {{goods[2].name}}
                </td>
                <td>
                    单价 {{goods[2].price}}
                </td>
                <td>
                    <button @click="subtraction(2)">-</button>
                    {{goods[2].num}}
                    <button v-on:click="add(2)">+</button>
                </td>
            </tr>
            <tr>
                <td>
                    {{sum}}
                </td>
            </tr>
        </table>
    </div>
    <script>
        const vm = new Vue({
            el: "#aaa",
            data() {
                return {
                    goods: [
                        { name: "西游记", price: 23, num: 0 },
                        { name: "水浒传", price: 27, num: 0 },
                        { name: "三国演义", price: 40, num: 0 },
                    ],
                    sum:0
                };
            },
            methods: {
                subtraction(index){
                    if(this.goods[index].num < 1){
                        alert("数量不能小于0")
                        return
                    }
                    this.goods[index].num -= 1;
                    this.sum -= this.goods[index].price
                },
                add(index){
                    this.goods[index].num += 1;
                    this.sum += this.goods[index].price
                }
            }
        })
    </script>
</body>

</html>